#ifndef SERIAL_COMMUNICATION_H
#define SERIAL_COMMUNICATION_H

#include <iostream>
#include <vector>
#include <thread>
#include <chrono>
#include <mutex>
#include <fstream>
#include <iomanip>
#include <boost/asio.hpp>
#include <boost/system/system_error.hpp>

class SerialWrapper
{
public:
    SerialWrapper(const std::string &port, unsigned int baudrate, boost::asio::serial_port_base::character_size bytesize,
                  boost::asio::serial_port_base::parity parity, boost::asio::serial_port_base::stop_bits stopbits);

    bool open_serial();
    void close();
    void write_data(const std::vector<uint8_t> &data);
    void read_data();
    void calculate_speed();
    void ensure_file_exists(const char* file_name);

private:
    void process_received_data(uint8_t *data, size_t length);
    void save_to_csv(int measurement, double time_diff, double speed);
    std::string stop_bits_to_string(boost::asio::serial_port_base::stop_bits stopbits);
    std::string parity_to_string(boost::asio::serial_port_base::parity parity);

    std::string port;
    unsigned int baudrate;
    boost::asio::serial_port_base::character_size bytesize;
    boost::asio::serial_port_base::parity parity;
    boost::asio::serial_port_base::stop_bits stopbits;
    boost::asio::io_service io;
    boost::asio::serial_port serial;

    std::vector<uint8_t> data_queue;
    std::mutex data_mutex;
    bool running = true;

    int last_measurement = 0;
    int current_measurement = 0;
    std::chrono::steady_clock::time_point last_time;
    std::chrono::steady_clock::time_point current_time;
    const int measure_interval = 100; // Interval in milliseconds
};

#endif // SERIAL_COMMUNICATION_H
